	
<template>
  <div>
    <van-nav-bar
      title="购物车"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <van-swipe-cell v-for="item in cartList" :key="item.id">
      <van-card
        :num="item.num"
        :price="item.price"
        :title="item.name"
        class="goods-card"
      >
        <template #thumb>
          <div class="left-thumb">
            <van-checkbox
              v-model="item.state"
              @click="onSingleCheck"
            ></van-checkbox>
            <img :src="item.url" alt="" width="70%" />
          </div>
        </template>
        <template #footer>
          <van-stepper v-model="item.num" theme="round" button-size="22" />
        </template>
      </van-card>

      <template #right>
        <van-button square text="删除" type="danger" class="delete-button" @click="onDelete(item.id)"/>
      </template>
    </van-swipe-cell>
    <van-submit-bar
      :price="totalPrice"
      button-text="提交订单"
      @submit="onSubmit"
    >
      <van-checkbox :value="stateAll" @click="onCheckAll">全选</van-checkbox>
      <template #tip>
        你的收货地址不支持同城送,
        <span @click="onClickEditAddress">修改地址</span>
      </template>
    </van-submit-bar>
  </div>
</template>

<script>
export default {

  computed: {
    cartList() {
      return this.$store.getters.cartList;
    },
    stateAll(){
      return this.$store.getters.stateAll;
    },
    //计算总价
    totalPrice() {
      let total = this.cartList.reduce(
        (prevous, current) => prevous + (current.state? current.price * current.num:0),
        0
      );
      return total * 100;
    },
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1);
    },
    onSubmit() {},
    onClickEditAddress() {},
    //单选状态
    onSingleCheck() {
      //  1.在商品数组中找到商品，更改状态state, 2. 根据所有单选状态设置全选状态
      let stateAll = this.cartList.every((item) => item.state);
      this.$store.dispatch("setStateAll", stateAll);
    },
    //全选状态
    onCheckAll() {
      // 1. 设置全选状态stateAll
      this.$store.dispatch("setStateAll", !this.stateAll);
      // 2. 所有单选状态
      this.cartList.forEach(item=>item.state=this.stateAll)
    },
    //删除商品
    onDelete(id){
       let index = this.cartList.findIndex(item=> item.id == id)
       this.cartList.splice(index,1)
    }
  },
};
</script>

<style >
.goods-card {
  margin: 0;
  background-color: white;
}

.delete-button {
  height: 100%;
}
.left-thumb {
  display: flex;
}
</style>
